import React, {Component} from 'react';
import Store from "../../../ReactReaux/store/cart_store"
import {addProduct,deleteProduct,updateProduct} from "../../../ReactReaux/actions/Cart_actions";
class ReduxOne extends Component {
    constructor(props) {
        super(props);
        this.listenter=''
        this.state={
            //本组件的数据源数据
            dataArray:Store.getState().productArray,
            id:0,
            name:"",
            price:"",
            count:0,
        }
    }
    render() {
        return (
            <div>
               <h1>这是one</h1>
                <ul>
                    <li><input type={"number"} placeholder={"请输入id"} min={1} onChange={this.inputId.bind(this)}/></li>
                    <li><input type={"text"} placeholder={"请输入商品名"}  onChange={this.inputname.bind(this)}/></li>
                    <li><input type={"number"} placeholder={"请输入价格"} min={0} onChange={this.inputPrice.bind(this)}/></li>
                    <li><input type={"number"} placeholder={"请输入数量"} min={1} onChange={this.inputnum.bind(this)}/></li>
                    <li><button onClick={this.addProduct.bind(this)}>提交</button></li><button onClick={this.updateclick.bind(this)}>更新</button>
                </ul>
                <h1>商品</h1>
                {this.state.dataArray.map((v,i)=>{
                    return <li key={i}>
                        id:{v.id} 商品名:{v.name} 价格:{v.price} 数量:{v.count} <button onClick={this.deleteclick.bind(this,v.id)}>删除</button>
                    </li>
                })}
            </div>
        );
    }
    inputId(e){
console.log(e.currentTarget.value)//获取输入框的值
        this.setState({
            id:e.currentTarget.value
        })
    }
    inputname(e){
        this.setState({
            name:e.currentTarget.value
        })
    }
    inputPrice(e){
        this.setState({
            price:e.currentTarget.value
        })
    }
    inputnum(e){
        this.setState({
            count:e.currentTarget.value
        })
    }
    addProduct(){
        console.log("jlak")
Store.dispatch(addProduct(this.state.id-0,this.state.name,this.state.price-0,this.state.count-0));
    }
    deleteclick(id){
        console.log(id)
        Store.dispatch(deleteProduct(id-0))
    }
    updateclick(){

        Store.dispatch(updateProduct(this.state.id-0,this.state.name,this.state.price-0,this.state.count-0))
    }


    componentDidMount() {
        //   设置redux 的监听
    this.listenter= Store.subscribe(()=>{
            // console.log("-------------");
            this.setState({
                dataArray:Store.getState().productArray
            })
        })
        // console.log(this.state.dataArray);
    }

    componentWillUnmount() {
        this.listenter();
    }
}

export default ReduxOne;